//
//  HMHomdController.swift
//  webo
//
//  Created by apple on 2016/11/12.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import JPFPSStatus
import SVProgressHUD
private let originalid = "StatusCellid"
private let tranmitid = "HMStatusTranmitID"
let orginalCell = UINib(nibName: "HMStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatusCell
let tranmitCell = UINib(nibName: "HMStatusTranmit", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatusCell

class HMHomdController: HMBaseTableViewController {
    lazy var needLoadArray: [IndexPath] = [IndexPath]()
    var count = 0

    //去过不是懒加载，视图会创建吗？？？？？、
    lazy var homeviewModel: HMHomeViewModel = HMHomeViewModel()
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        return indicator
    }()
    lazy var tipLabel: UILabel = {
        let l = UILabel(text: "", fontSize: 16, numbLines: 0, tcolor: UIColor.white)
        l.backgroundColor = UIColor.orange
        l.textAlignment = .center
        l.isHidden = true;
        return l
    }()
    lazy var hmrefreshcontrol:HMRefreshControl = HMRefreshControl()
    override func viewDidLoad() {
        super.viewDidLoad()
        //没有登入
        JPFPSStatus.sharedInstance().open()
        
        if !islogin {
            loginView.updateMessage(lblText: "关注一些人，回到这里看看有什么惊", circleImgName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
        }
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: #selector(push))
        
        setupUI()
        
        loadData()
    }
    //点击push
    func push(){
        self.navigationController?.pushViewController(HMHomdeDemoController(), animated: true)
        
    }
    
    private func setupUI(){
        //注册
        tableView.register(UINib.init(nibName: "HMStatusCell", bundle: nil), forCellReuseIdentifier: originalid)
        tableView.register(UINib.init(nibName: "HMStatusTranmit", bundle: nil), forCellReuseIdentifier: tranmitid)
        
        //        高度
        //        tableView.rowHeight = 300
        tableView.tableFooterView = indicatorView
        //        self.refreshControl = HMRefreshControl()
//        let hmrefresh = HMRefreshControl()
        self.view.addSubview(hmrefreshcontrol)
        hmrefreshcontrol.addTarget(self, action: #selector(loadData), for: .valueChanged)
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        tipLabel.frame.origin.y = naviBarHeight - 35
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        
        NotificationCenter.default.addObserver(self, selector: #selector(receiveVisitNetworkFail), name: NSNotification.Name(visitNetworkFaile) , object: nil)
    }
    
    func loadData(){
        homeviewModel.loadData(isPullUp: indicatorView.isAnimating) { (isSucceed, count) in
            if !isSucceed{
                return
            }
            self.indicatorView.stopAnimating()
//            self.refreshControl?.endRefreshing()
            self.hmrefreshcontrol.endAnimation()
            if self.indicatorView.isAnimating == false{
            self.startTintLabelAnimation(count: count)
            }
            self.tableView.reloadData()
        }
    }
    
    @objc private func receiveVisitNetworkFail(){
        self.indicatorView.stopAnimating()
        self.hmrefreshcontrol.endAnimation()
        if tipLabel.isHidden != true {
            return
        }
        tipLabel.isHidden = false
        tipLabel.text = "刷新网络失败"
        startLabelAnimation()
    }
    
    func startTintLabelAnimation(count: Int){
        if tipLabel.isHidden != true {
            return
        }
        tipLabel.isHidden = false
        tipLabel.text = (count == 0 ? "已经是最新" : "刷新了\(count)")
        startLabelAnimation()
    }
    private func startLabelAnimation(){
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = naviBarHeight
        }) { (hao) in
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (haode) in
                self.tipLabel.isHidden = true
            })
        }
 
    }
    
}


//extension HMOAuthViewController: UIWebViewDelegate{
//extension QQListTVC {

extension HMHomdController{
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeviewModel.viewmodelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        let cell = tableView.dequeueReusableCell(withIdentifier:cellid for: indexPath)
        let viewmodel = self.homeviewModel.viewmodelArray[indexPath.row]
       
        let cellID = viewmodel.status?.retweeted_status == nil ? originalid : tranmitid
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! HMStatusCell
        
        //如果需要加载的数组的数量大于0 并且 正要加载的indexPath不在按需加载的数组中 就不渲染cell
        if needLoadArray.count > 0 {
            let result = needLoadArray.contains(where: { (index) -> Bool in
                return index.row == indexPath.row && index.section == indexPath.section
            })
            if !result {
                print("^    😈😈😈😈😈😈😈打酱油😈😈😈😈😈😈")
                return cell
            }
        }
        
        cell.viewModel = homeviewModel.viewmodelArray[indexPath.row]
        
        return cell
    }
    override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
}
//代理
extension HMHomdController{

//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        let status: HMStatusViewModel = homeviewModel.viewmodelArray[indexPath.row]
//        let cell = status.status?.retweeted_status != nil ? tranmitCell : orginalCell
//        cell.viewModel = status
//        
//        cell.layoutIfNeeded()
//        print(cell.uv_bottomTool.frame.maxY)
//        return cell.uv_bottomTool.frame.maxY
//    }
    
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indicatorView.isAnimating == false && indexPath.row == homeviewModel.viewmodelArray.count - 1 {
            indicatorView.startAnimating()
            self.loadData()
        }
    }
    
    
    
    
    //如果在这里完成自定刷新控件UI的更新, 这就是强耦合
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        
        let skipCount = 12;
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: self.view.frame.width, height: self.view.frame.height)) else {
                
                return
            }
            var arr = temp
            print(velocity.y)
            //向下滑动
            if velocity.y < 0 {
                
                let indexPath = temp.last!
                if (indexPath.row + 3 < self.homeviewModel.viewmodelArray.count) {
                    arr.append(IndexPath(row: indexPath.row + 1, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 3, section: 0))
                }
            }else{
                //向上滑动
                let indexPath = temp.first!
                if (indexPath.row > 3) {
                    arr.append(IndexPath(row: indexPath.row - 3, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 1, section: 0))
                }
            }
            needLoadArray.append(contentsOf: arr)
        }
    }
    
    
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }

    //先调用获取行高的协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获取cell
        count = count + 1
        print(count)
        let viewmodel = self.homeviewModel.viewmodelArray[indexPath.row]
        
        return viewmodel.rowHeight
    }
}


